# -*- coding:utf-8 -*-
from django.shortcuts import render, redirect
from django.http import HttpResponse

# Create your views here.
from .models import Column, Article

# 分页
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage


def index(request):
    # return HttpResponse(u'Welcome Study Python Django')
    # columns = Column.objects.all()
    # return render(request, 'index.html', {'columns': columns})
    home_display_columns = Column.objects.filter(home_display=True)
    nav_display_columns = Column.objects.filter(nav_display=True)
    return render(request, 'index.html', {
        'home_display_columns': home_display_columns,
        'nav_display_columns': nav_display_columns,
    })

def column_detail(request, column_slug):
    # return HttpResponse('column slug: ' + column_slug)
    column = Column.objects.get(slug = column_slug)

    # 分页
    article_list = column.article_set.all()
    paginator = Paginator(article_list, 2)
    page = request.GET.get('page')
    try:
        articles = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        articles = paginator.page(1)
    except EmptyPage:
        # If page is out of range(e.g. 9999), deliver last page of results.
        articles = paginator.page(paginator.num_pages)

    return render(request, 'news/column.html', {'column': column, 'object_list': articles})

def article_detail(request, pk, article_slug):
    # return HttpResponse('article slug: ' + article_slug)
    # article = Article.objects.get(slug = article_slug)
    # article = Article.objects.filter(slug = article_slug)[0]
    article = Article.objects.get(pk = pk)

    if article_slug != article_slug:
        return redirect(article, parmanent=True)

    return render(request, 'news/article.html', {'article': article})